/*
 * Title: WADS
 * Description: Web-based Auto flow Documents System
 * Copyright: 2007
 * Company: CoE
 * @author: Mr.Nattasan Wang-Aphisit
 * @version 1.1
 */

package wads.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wads.com.UserInfo;
import wads.com.UserInfoDataStruct;
import wads.com.WADTools;
import wads.database.DbConnector;
import wads.database.Derby;
import wads.database.MySql;

public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = -7710347205992990371L;
  
  private static final String CONTENT_TYPE = WADTools.SERVLET_CONTENT_TYPE;
  /**Initialize global variables*/
  public static final int DEFAULT = 0;
  public static final int POWERUSER = 1;
  public static final int RESTRICTUSER = 2;
  public static final int ADMINUSER = 3;

  HttpSession session;
//  private String restrictUserFile;
//  private String powerUserFile;
//  private String app_Path;
//  private ObjectInputStream ois;
  private UserInfo uiRestrictUser;
  private UserInfo uiPowerUser;
  private Properties prop = new Properties();
  private String orgName;
  private MySql db;
  
  @Override
  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }

  /**Process the HTTP Post request*/
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType(CONTENT_TYPE);

    db = new MySql();
    int checkLogin = DEFAULT;
//    app_Path = WADTools.APP_PATH;
    String uName = "";
    try {
      uName = request.getParameter("UserName");
    }
    catch(Exception e) {
      System.out.println("Exception thrown when LoginServlet try to get Username parameter.");
      e.printStackTrace();
    }
    
    String uPass = "";
    try{
      uPass = request.getParameter("Password");
    }
    catch(Exception e) {
      System.out.println("Exception thrown when LoginServlet try to get Password parameter.");
      e.printStackTrace();
    }

    session = request.getSession(true);
    session.removeAttribute("UserName");

//      System.out.println(WADTools.getShareAppData()+"/"+WADTools.CONFIG_FILENAME);

    prop.load(new FileInputStream(WADTools.getShareAppData()+"/"+WADTools.CONFIG_FILENAME));
//    prop.load(new FileInputStream("E:/ProjectII/WADS/WADSApp/res/wad_app.properties"));
    orgName = prop.getProperty("orgName", "No");
    System.out.println("OrganizationName = " + orgName);

//    restrictUserFile = app_Path+"res/user/RestrictUser/RestrictUser.org";
//    powerUserFile = app_Path+"res/user/PowerUser/" + orgName;

    //Read Object of RestrictUser
//    try{
//      ois = new ObjectInputStream(new FileInputStream(restrictUserFile));
//      uiRestrictUser = (UserInfo)ois.readObject();
//      ois.close();
//    }catch(Exception e){
//      System.out.println("Exception thrown when LoginServlet try to read RU information from file.");
//    }
//
//    try{
//      ois = new ObjectInputStream(new FileInputStream(powerUserFile));
//      uiPowerUser = (UserInfo)ois.readObject();
//      ois.close();
//    }catch(Exception e){
//      System.out.println("Exception thrown when LoginServlet try to read PU information from file.");
//    }

    uiPowerUser = db.loadUsers(DbConnector.POWER_USER);
    uiRestrictUser = db.loadUsers(DbConnector.RESTRICT_USER);
    
    //Check restrictUserName and restrictUserPassword
    for(int i=0; i<uiRestrictUser.getSize(); i++){
      if(uName.equals(uiRestrictUser.getUserDataAt(i).getUsername())){
        if(uiRestrictUser.getUserDataAt(i).isPasswordMatch(WADTools.encryptPassword(uPass.toCharArray()))){
          checkLogin = RESTRICTUSER;
        }
      }
    }

    //Check powerUserName and powerUserPassword
    for(int i=0; i<uiPowerUser.getSize(); i++){
      if(uName.equals(uiPowerUser.getUserDataAt(i).getUsername())){
        if(uiPowerUser.getUserDataAt(i).isPasswordMatch(WADTools.encryptPassword(uPass.toCharArray()))){
          checkLogin = POWERUSER;
        }
      }
    }

    //check AdminUser and AdminPassword
    UserInfoDataStruct admin = db.loadUsers(Derby.ADMIN).getUserDataAt(0);
//    if((uName.equals(admin.getUsername())) && (WADTools.isPasswordMatch(uPass.toCharArray(), adminpass))){
    if(uName.equals(admin.getUsername()) && admin.isPasswordMatch(WADTools.encryptPassword(uPass.toCharArray()))){
      checkLogin = ADMINUSER;
    }

    switch(checkLogin){
      case POWERUSER:
        session.setAttribute("UserName", uName);
        response.sendRedirect("/WADSWeb/applet.jsp");
        break;
      case RESTRICTUSER:
        session.setAttribute("UserName", uName);
        response.sendRedirect("/WADSWeb/start.jsp");
        break;
      case ADMINUSER:
        session.setAttribute("UserName", uName);
        response.sendRedirect("/WADSWeb/admin.jsp");
        break;
      default:
        session.setAttribute("UserName", "");
        response.sendRedirect("/WADSWeb/login_false.jsp");
    }
  }
  /**Clean up resources*/
  @Override
  public void destroy() {
  }
}
